import { createRouter, createWebHistory } from 'vue-router';
import Login from '../views/Login.vue';
import Dashboard from '../views/Dashboard.vue';
import UserManagement from '../views/UserManagement.vue';
import CategoryManagement from '../views/CategoryManagement.vue';
import VideoManagement from '../views/VideoManagement.vue';
import CommentManagement from '../views/CommentManagement.vue';
import VideoTypeManagement from '../views/VideoTypeManagement.vue';
import Settings from '../views/Settings.vue';

const routes = [
  {
    path: '/',
    redirect: '/login'
  },
  {
    path: '/login',
    name: 'Login',
    component: Login,
    meta: { requiresAuth: false }
  },
  {
    path: '/dashboard',
    name: 'Dashboard',
    component: Dashboard,
    meta: { requiresAuth: true }
  },
  {
    path: '/users',
    name: 'UserManagement',
    component: UserManagement,
    meta: { requiresAuth: true }
  },
  {
    path: '/categories',
    name: 'CategoryManagement',
    component: CategoryManagement,
    meta: { requiresAuth: true }
  },
  {
    path: '/video-types',
    name: 'VideoTypeManagement',
    component: VideoTypeManagement,
    meta: { requiresAuth: true }
  },
  {
    path: '/videos',
    name: 'VideoManagement',
    component: VideoManagement,
    meta: { requiresAuth: true }
  },
  {
    path: '/comments',
    name: 'CommentManagement',
    component: CommentManagement,
    meta: { requiresAuth: true }
  },
  {
    path: '/settings',
    name: 'Settings',
    component: Settings,
    meta: { requiresAuth: true }
  }
];

const router = createRouter({
  history: createWebHistory(),
  routes
});

// 路由守卫
router.beforeEach((to, _from, next) => {
  const requiresAuth = to.matched.some(record => record.meta.requiresAuth);
  const token = localStorage.getItem('token');
  
  if (requiresAuth && !token) {
    next('/login');
  } else if (!requiresAuth && token) {
    next('/dashboard');
  } else {
    next();
  }
});

export default router;